package org.vectrics.mail.struts;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.ecs.html.A;
import org.apache.ecs.html.Div;
import org.apache.ecs.html.TextArea;
import org.vectrics.SystemException;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Combo;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.util.StringUtils;
import org.vectrics.common.view.HtmlForm;
import org.vectrics.common.view.HtmlFormComboRow;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.mail.FileEmailTemplate;
import org.vectrics.mail.FileEmailTemplateCategory;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;
import org.vectrics.user.PersonNameComparator;
import org.vectrics.user.PersonSearchCriteria;

/**
 * @author Mike Moore
 *
 */
public class BulkEmailFormTag extends VectricsTagSupport {

	private static final long serialVersionUID = 2504579144973548594L;
	
	public static String ACTION_FORM_NAME = "bulkEmailForm";  // Value in struts-config of form.
	public static String CATEGORY_SELECT_COMBO_NAME = "categoryId";
	public static String TEMPLATE_SELECT_COMBO_NAME = "templateId";
	public static String TEMPLATE_SAVED_POPUP_DIV = "template_saved_popup_div";	
	public static String FORM_ID = ACTION_FORM_NAME;
	
	/**
	 * 
	 */
	public BulkEmailFormTag() {
		super();
	}
	
	/* (non-Javadoc)
	 * @see org.vectrics.struts.VectricsTagSupport#makeStartTag()
	 */
	@Override
	protected String makeStartTag() {
		
		BulkEmailForm bulkEmailForm = null; //(BulkEmailForm)this.getRequest().getAttribute(ACTION_FORM_NAME);
		if (bulkEmailForm == null) {
			bulkEmailForm = new BulkEmailForm();
		}
		
		HtmlForm htmlForm = new HtmlForm(this.getRequest(), ACTION_FORM_NAME, this.getPhrase("phrase.mail.template"));
		htmlForm.setId(FORM_ID);
		htmlForm.setAction("/hrs-intranet/admin/mailer/stage.do");
		Combo combo = new Combo();
		combo.addOption(getPhrase("phrase.select.option"), "0");
		List<FileEmailTemplateCategory> categories = CoreServiceLocator.getSystemService().findAllEmailTemplateCategories(ThreadProperties.getDomain());
		Iterator<FileEmailTemplateCategory> iter = categories.iterator();
		while (iter.hasNext()) {
			FileEmailTemplateCategory category = iter.next();
			combo.addOption(category.getDescription(), category.getId().toString());
		}
		combo.setOnChange("refreshTemplateCombo();");
		HtmlFormComboRow comboRow = htmlForm.addComboRowForParam("Template Category", CATEGORY_SELECT_COMBO_NAME, combo, true);
		//comboRow
		
		combo = new Combo();
		Long templateId = null;

		if (StringUtils.isNullOrBlank(bulkEmailForm.getTemplateId()) == false) {
			templateId = new Long(bulkEmailForm.getTemplateId());
		}
		if (StringUtils.isNullOrBlank(bulkEmailForm.getCategoryId()) == false) {
			log.debug("Category id was passed, filling template combo with templates from the selected category.  Category=" + bulkEmailForm.getCategoryId());
			Domain domain = ThreadProperties.getDomain();
			FileEmailTemplateCategory fileEmailTemplateCategory 
 			     = CoreServiceLocator.getSystemService().findFileEmailTemplateCategory(new Long(bulkEmailForm.getCategoryId()));
			List<FileEmailTemplate> templates = CoreServiceLocator.getSystemService().findEmailTemplatesForCategory(domain, fileEmailTemplateCategory);
			Iterator<FileEmailTemplate> templateIter = templates.iterator();
			while (templateIter.hasNext()) {
				FileEmailTemplate template = templateIter.next();
				combo.addOption(template.getDescription(), template.getId().toString());
				
				if ((templateId != null) && (template.getId().equals(templateId))) {
					combo.selectOption(template.getId().toString());
				}
			}
		}
		htmlForm.addComboRowForParam("Template", TEMPLATE_SELECT_COMBO_NAME, combo, true);

		TextArea templateTextArea = htmlForm.addTextAreaRowForParam("Message Text", "templateText", 15, 60, false);
		templateTextArea.setOnChange("templateTextChanged();");
		
		String saveTemplateMethod = "javascript:saveTemplateText();";
		
		htmlForm.addEditForParam("Subject", "subject", true);
		htmlForm.addButton("Save Template", saveTemplateMethod, "std.button", "save.template");
		//htmlForm.addSubmitAndCancelButton();
		String sendMethod = "javascript:sendToRecipients();";
		htmlForm.addButton("Send", sendMethod, "std.button", "send.email");
		
		htmlForm.addColumn(this.getPhrase("phrase.recipients"));

		addPassedTemplateParametersToForm(htmlForm, this.getRequest());
		
		Div parentRecipientDiv = new Div();
		parentRecipientDiv.setClass("emailRecipientParentDiv");
		parentRecipientDiv.setID("div_recipient_holder");
		htmlForm.addElement(parentRecipientDiv);
		htmlForm.addHidden("sender_id", ThreadProperties.getPerson().getId().toString());
		htmlForm.addHidden("templateParameterLoader", this.getRequest().getParameter("templateParameterLoader"));
		String addRecipientMethod = "javascript:pickRecipientToAdd();";
		htmlForm.addButton("Add Recipient", addRecipientMethod, "std.button", "add.recipient");
		
		StringBuffer html = new StringBuffer();

		TreeSet<Person> sortedRecipients = new TreeSet<Person>(new PersonNameComparator());
		String searchParam = this.getRequest().getParameter("usePersonSearchCriteria");
		if (StringUtils.isNullOrBlank(searchParam) == false) {
			PersonSearchCriteria criteria = (PersonSearchCriteria)this.getRequest().getSessionAttribute("userSelectCriteria");
			sortedRecipients.addAll(CoreServiceLocator.getPersonSearcher().findPersons(criteria, 0, 1000));
		} 
		
		//recipientList.add(this.getAuthPerson());
		Iterator<String> paramIter = this.getRequest().getParameterNames().iterator();
		while (paramIter.hasNext()) {
			String paramName = paramIter.next();
			if (paramName.startsWith("recip_")) {
				String recipParam = paramName.substring("recip_".length());
				log.info("Passed recpipient: " + recipParam);
				Long recipPersonId = new Long(recipParam);
				Person recipient = CoreServiceLocator.getPersonService().findPersonById(recipPersonId);
				sortedRecipients.add(recipient);
			}
		}

		Set<String> attributeNames = this.getRequest().getAttributeNames();
		Iterator<String> attrIter = attributeNames.iterator();
		while (attrIter.hasNext()) {
			String attributeName = attrIter.next();
			if (attributeName.startsWith("recip_")) {
				String recipParam = attributeName.substring("recip_".length());
				log.info("Passed recpipient: " + recipParam);
				Long recipPersonId = new Long(recipParam);
				Person recipient = CoreServiceLocator.getPersonService().findPersonById(recipPersonId);
				sortedRecipients.add(recipient);
			}
		}
		createJavaScript(html, sortedRecipients);
		html.append(htmlForm.toString());
		makeTemplateSavedPopup(html);
		createEndJavaScript(html);
		
		html.append(createGraphTree());
		return (html.toString());
	}

	
	private String createGraphTree() {
		StringBuffer html = new StringBuffer();
		log.info("createGraphTree");
		ObjectGraph objectGraph = (ObjectGraph)this.getRequest().getSessionAttribute("freemarkerObjectGraph");
		if (objectGraph == null)
			throw new SystemException("Could not find freemarkerObjectGraph attached to session");

		Set<String> keys = objectGraph.getKeys();
		if (keys.size() > 0) {
			html.append("<h3>Template Objects</h3>");
			Table table = new Table();
			table.setWidth(600);
			Iterator<String> keyIter = keys.iterator();
			while (keyIter.hasNext()) {
				String key = keyIter.next();
				TemplateObject object = objectGraph.getObject(key);
				this.addObjectToGraphDisplay(object, table, key, 1, 4, key);
			}
			html.append(table.toString());
		}
		
		return html.toString();
	}

	
	private void addObjectToGraphDisplay(TemplateObject object, Table table, String key, int depth, int maxDepth, 
			String fullKeyPath) {
		log.info("Adding to objectGraph display: " + key + "  Depth: " 
				+ depth + "  Object Type: " + object.getClass().getName());
		if (depth > maxDepth) {
			return;
		}

		String indentStr = "";
		for (int d = 0; d < depth; d++) {
			indentStr  += "*&nbsp;";
		}
		String objectValue = null;
		try {
			objectValue = object.toString();
		} catch (Exception ex) {
			log.warn("Exception finding object value: " + fullKeyPath + " - " + ex.getMessage());
		}
		String href = this.getContextPath() + "/admin/mailer/edit/object_graph.do?object_key=" + key;

		A viewObjectLink = new A();
		viewObjectLink.setClass("stdFont");
		viewObjectLink.setHref(href);
		viewObjectLink.setOnClick("OpenLarge(this.href, '138'); return false");
		viewObjectLink.addElement(fullKeyPath);

		Row row = table.addRow();
		Cell cell = row.addCell();
		cell.addElement(viewObjectLink);
		
		cell = row.addCell();
		cell.addText("stdFont", object.getName());
	}

	private void makeTemplateSavedPopup(StringBuffer html) {
		String body = "The template has been saved.";
		int left = 200;
		int top = 100;
		int width = 350;
		int height = 250;
		int captionHeight = 20;
		int buttonHeight = 20;
		int buttonWidth = 90;
		int bodyHeight = height - (captionHeight + buttonHeight);
		html.append("<div style=\"visibility: hidden;position:absolute; top:" + top + 
				"px; left:" +
				 left + "px; width:" + width + "px; height:" +
				 		height + "px;text-align:center; padding:0px;z-index:100;\"");
		html.append(" id=\"" + TEMPLATE_SAVED_POPUP_DIV +
				"\">\r\n");
		html.append("	<IFRAME style=\"POSITION: absolute; TOP:0px; LEFT:0px; WIDTH:" +
				  width + "px" +
				 		"; HEIGHT:" + height +
				 		"px; z-index=98\"\r\n");
		html.append("	  src=\"javascript:a=1;\"");
		html.append("	  frameBorder=\"0\" scrolling=\"no\">\r\n");
		html.append("	</IFRAME>\r\n");
		html.append("	\r\n");
		html.append("	<div  style=\"position:absolute; top:0px; left:0px; width: " + (width + 10) + "\r\n");
		html.append("			background-color:#faffe8; text-align:left; padding:0px;border: solid 3px #339999;\r\n");
		html.append("			z-index:99;\">\r\n");
		html.append("       <div style=\"text-align:left; background-color:#f0ebc0; height: " + captionHeight + "\">&nbsp;Information</div>\r\n");
		html.append("    	<div style=\"padding:4\">\r\n");
		html.append("          <div style=\"text-align:center;height:" + bodyHeight + "\">" + body + "</div>\r\n");
		html.append("       </div>\r\n");
		html.append("       <div style=\"pobackground-color:#f0ebc0;height:" + buttonHeight + "\" onclick='javascript:hideTemplateSavedDialog()'>\r\n");
		html.append("            <img src=\"/hrs-intranet/dynagraphic/button.jpg?code=button.ok&caption=Ok\" alt=\"\" height=\"" +
				buttonHeight + "\" width=\"" +
						buttonWidth + "\" border=\"0\" />");
		html.append("     	</div>\r\n");
		html.append("	</div>\r\n");
		html.append("</div>\r\n");
	}	
	
	/**
	 * 
	 * @param htmlForm
	 * @param request
	 */
	private void addPassedTemplateParametersToForm(HtmlForm htmlForm, Request request) {
		// Add passed template parameters
		GetRequestTemplateParameterLoader getLoader = new GetRequestTemplateParameterLoader(); 
		TemplateParameterLoader parameterLoader = getLoader.load(request);
		Map<String, String> parameterMap = new HashMap<String, String>();
		parameterLoader.loadParameters(request, parameterMap);

		Set<String> mapKeys = parameterMap.keySet();
		Iterator<String> iter = mapKeys.iterator();
		while (iter.hasNext()) {
			String parameterName = iter.next();
			log.info("Getting value for template parameter named: " + parameterName);
			String parameterValue = parameterMap.get(parameterName);
			htmlForm.addHidden("tmplt_" + parameterName, parameterValue);
		}
	}	

	/*
	private Map<String, Object> getReportParameterMap(Person sender) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sender", sender);
		map.put("sendDate", new Date());
		return(map);
	}
	*/

	
	private void createEndJavaScript(StringBuffer html) {
		html.append("<script type=\"text/javascript\">\r\n");
		html.append("   refreshRecipientListDisplay();\r\n");
		html.append("</script>\r\n");
	}
	
	/**
	 * Create JavaScript for dynamic behavior in form.
	 * @param html
	 */
	private void createJavaScript(StringBuffer html, Set<Person> recipientList) {
		List<FileEmailTemplateCategory> categories 
			= CoreServiceLocator.getSystemService().findAllEmailTemplateCategories(ThreadProperties.getDomain());

		
		// DIV to hold form that is built when needed to submit changes in an AJAX way to
		// the server.  None of this should be visible
		html.append(
				"<div id=\"save_temp_text_holder\">\r\n" +
				"  <form id=\"form_temp_text\" action=\"savetemplatejs.do\" method=\"post\">\r\n" +
				"	  <input id=\"temp_form_text_hdn\" type=\"hidden\" name=\"text\" value=\"\"/>\r\n" +
				"	  <input id=\"temp_form_id_hdn\" type=\"hidden\" name=\"id\" value=\"\"/>\r\n" +
				"  </form>\r\n" +
				"</div>\r\n");
		
		html.append("<script type=\"text/javascript\">\r\n");
		html.append("\r\n\r\n  // Created by " + this.getClass().toString() + ".addTemplateComboArray()\r\n");
		html.append("var recipientList = new Array(100);\r\n");
		html.append("var templateNeedsSave = false;\r\n");
		html.append(
				" function templateTextChanged() { \r\n" +
				"    log('templateTextChanged() called');\r\n" +
				"    templateNeedsSave = true;\r\n" +
				" }   \r\n\r\n");
		
		html.append(
				" function addRecipientData(id, lastName, firstName) { \r\n" +
				"    log('addRecipientData() called');\r\n" +
				"    var length = recipientList.length;\r\n" +
				"    var person = new Array(4);\r\n" +
				"    recipientList[length] = person;\r\n" +
				"    person[0] = id;\r\n" +
				"    person[1] = lastName;\r\n" +
				"    person[2] = firstName;\r\n" +
				" }   \r\n\r\n");

		html.append("//###################################################\r\n");
		html.append("// Initial recient list\r\n");
		Iterator<Person> iter = recipientList.iterator();
		while (iter.hasNext()) {
			Person recipient = iter.next();
			html.append("var person = new Array(4);\r\n");
			html.append("recipientList[" + recipient.getId() + "] = person;\r\n");
			html.append("addRecipientData(" + recipient.getId() + ", '" + recipient.getLastName() 
					+ "', '" + recipient.getFirstName() + "&nbsp;" + recipient.getMiddleName() + "');\r\n");
		}
		html.append("//####################################################\r\n");
		html.append("   var categoryTemplates = new Array(" +
				 categories.size() + ")\r\n;");
		html.append("                \r\n");
		addTemplateComboArray(html, categories);
		
		html.append(
				" function sortRecipientList(recipientList) { \r\n" +
				"    var sortedList = new Array(recipientList.length);\r\n" +
				"    alert('sortRecipientList() - not implemented');\r\n" +
				"    return recipientList;\r\n" +
				"}\r\n\r\n");

		html.append(
				" function refreshRecipientListDisplay() { \r\n" +
				"   var normalRowColor = '#ffffff'; \r\n" +
				"   var selectRowColor = '#cccccc'; \r\n" +
				"   var quotedNormalRowColor = \"'\" + normalRowColor + \"'\";\r\n" +
				"   var quotedSelectRowColor = \"'\" + selectRowColor + \"'\";\r\n" +

				"   var resultsTable = '<table style=\"cursor: pointer\">';\r\n" +
				"   resultsTable += '<tr>' \r\n" +
				"   	+ '<td width=\"20\"><div class=\"subFont\"><b>Id</b></div></td>' \r\n" +
				"   	+ '<td width=\"80\"><div class=\"subFont\"><b>Last Name</b></div></td>' \r\n" +
				"   	+ '<td width=\"80\"><div class=\"subFont\"><b>First Name</b></div></td>' \r\n" +
				"   	+ '<td width=\"80\"></td>' \r\n" +
				"   	+ '</tr>';\r\n" +
				"     recipientCount = recipientList.length;\r\n" +
				"     log('recipient count = ' + recipientCount);\r\n" +
				"     for (i = 0; i < recipientCount; i++) { \r\n" +
				"       var recipient = recipientList[i];\r\n" +
				"       if ((recipient != null) && (recipient[0] != null)) {\r\n" +
				"   	   var quotedId = \"'\" + recipient[0] + \"'\";\r\n" +
				"          var middleName = recipient[1];\r\n" + 
				"          if ((middleName == 'null') || (middleName == null)) \r\n" +
				"              middlyeName = ''; \r\n" +
				"   	   var quotedName = \"'\" + recipient[2] + \" \" + middleName + \"'\" \r\n" +
				"   	   var trStr;\r\n" +
				"   	   trStr = '<tr' \r\n" +
				"   	   trStr += ' bgcolor='  + quotedNormalRowColor;\r\n" +
				//"   	   trStr += ' onClick="selectPersonItem(' + quotedId + ', ' + quotedName + ');"';
		        //"   	   trStr += ' onMouseOver="changeColor(this, '	+ quotedSelectRowColor + ');"';
		        //"   	   trStr += ' onMouseOut="changeColor(this, '	+ quotedNormalRowColor + ');"';
		        "   	   trStr += '>';\r\n" +

		        "   	   var detailStr = trStr   \r\n" +
		        "   		  + '<td><div class=\"subFont\">' + recipient[0] + '</div></td>'  \r\n" +
		        "   		  + '<td><div class=\"subFont\">' + recipient[1] + '</div></td>' \r\n" +
		        "   		  + '<td><div class=\"subFont\">' + recipient[2] + '</div></td>' \r\n" +
		        "   		  + '<td><div class=\"subLink\" onclick=\"removeRecipient(' + quotedId + ');\"/>remove</div></td>' \r\n" +
		        "   		  + '</tr>';\r\n" +
		        "   	   resultsTable += detailStr; \r\n" +
		        "       } \r\n" + 
		        "     } \r\n" +
		        "     resultsTable += '</table>'; \r\n" +
				"     var holderDiv = document.getElementById('div_recipient_holder');\r\n" +
				"     holderDiv.innerHTML = resultsTable;\r\n" +
				" }   \r\n\r\n");
		
		html.append(
				" function refreshTemplateCombo() { \r\n" +
				"    log('refreshTemplateCombo() called');\r\n" +
				"	 var categoryCombo = document.getElementById('categoryId'); \r\n" +
				"	 var templateComboDiv = document.getElementById('div_templateId'); \r\n" +
				"	 var categoryId = categoryCombo.value; \r\n" +
				"    log('refreshTemplateCombo() - categoryId = ' + categoryId);\r\n" +
				"    newTemplateComboText = categoryTemplates[categoryId];\r\n" +
				"    log(\"refreshTemplateCombo() - new combo text = \" + newTemplateComboText);\r\n" +
				"	 templateComboDiv.innerHTML = newTemplateComboText; \r\n" +
				"    log('refreshTemplateCombo() done');\r\n" +
				"	 if (categoryId > 0) { \r\n" +
				"        log('Get template text with call to server');\r\n" +
				"        getTemplateTextFromWeb();\r\n" +
				"    } else {\r\n" +
				"        log('User selected empty category, displaying blank text');\r\n" +
				"        displayTemplateText('');\r\n" +
				"    } \r\n" +
				" }   \r\n\r\n");
		

		html.append(
				"function getSelectedTemplateId() { \r\n" +
				"   log('getSelectedTemplateId() called'); \r\n" +
				"   var templateId = 0;\r\n" +
				"	var templateComboDiv = document.getElementById('div_templateId'); \r\n" +
				"   var divChildren = templateComboDiv.childNodes;\r\n" +
				"   if (divChildren.length > 0) {\r\n" +
				"      var templateCombo = templateComboDiv.firstChild; \r\n" +
				"      templateId = templateCombo.value;\r\n" + 
				"      log('getSelectedTemplateId() - templateId = ' + templateId); \r\n" +
				"   } else {\r\n" +
				"      alert('ERROR: getTemplateTextFromWeb() - could not find a child under template id div.'); \r\n" +
				"   } \r\n" +
				"   return(templateId);\r\n" +
			    "}\r\n\r\n");
		
		html.append(
				"function getTemplateTextFromWeb() { \r\n" +
				"   log('getTemplateTextFromWeb() called'); \r\n" +
				"   var templateId = getSelectedTemplateId();\r\n" + 
				"   log('getTemplateTextFromWeb() - make http request to get template text'); \r\n" +
				"   if (templateId > 0) { \r\n" +
				"      findEmailTemplateText('" +
 				           this.getContextPath() + 
							"', '" + this.getAuthPerson().getUser().getUserName() +
				            "', '" + ThreadProperties.getDomain().getId().toString() + 
				            "', '" + this.getAuthPerson().getUser().getPassword() +
				            "', templateId);\r\n" +
				"   } else { \r\n " +
				"       log('templateId not found, no attempt to retrieve text.  Template id: ' + templateId);" +
				"   } \r\n" +
			    "}\r\n\r\n");
		
		html.append(
                "function removeRecipient(personId) { \r\n" +
                "   recipient = findRecipient(personId);\r\n" +
                "   if (recipient != null) \r\n" +
                "      recipient[0] = null;\r\n" +
				"   refreshRecipientListDisplay();\r\n" +
                "} \r\n\r\n"); 
		
		html.append(
                "function sendToRecipients() { \r\n" +
				"	var form = document.getElementById('" + BulkEmailFormTag.FORM_ID + "'); \r\n" +
				"   var recipientCount = recipientList.length;\r\n" +
				"   log('sendToRecipients() - recipient count = ' + recipientCount);\r\n" +
				"   for (i = 0; i < recipientCount; i++) { \r\n" +
				"       var recipient = recipientList[i];\r\n" +
				"       if ((recipient != null) && (recipient[0] != null)) {\r\n" +
				"          var recipientHidden = document.createElement('input');\r\n" + 
				"          recipientHidden.type = 'hidden';\r\n" +
				"          recipientHidden.name = 'recip_' + recipient[0];\r\n" +
				"          recipientHidden.value = recipient[0];\r\n" +
				"          document.forms['" + BulkEmailFormTag.ACTION_FORM_NAME + "'].appendChild(recipientHidden);\r\n" + 
				"       };\r\n" + 
				"   };\r\n" + 
				"   log('submitting form()');\r\n" +
				"   form.submit();\r\n" + 
                "} \r\n\r\n"); 
		
		html.append(
				"function findRecipient(personId) {\r\n" +
				"     var foundRecipient = null;\r\n" +
				"     var recipientCount = recipientList.length;\r\n" +
				"     log('findRecipient() - recipient count = ' + recipientCount);\r\n" +
				"     for (i = 0; i < recipientCount; i++) { \r\n" +
				"       var recipient = recipientList[i];\r\n" +
				"       if (recipient != null) {\r\n" +
				"     	   if (recipient[0] == personId) {\r\n" +
				"             foundRecipient = recipient;\r\n" +
				"		   } else {  \r\n" +
				"              log('recipient did not match person id: ' + recipient[0]);\r\n" +
				"          };\r\n" +
				"     	}\r\n" +
				"     }\r\n" +
				"     return foundRecipient;" +
				"}\r\n"
				);
		
		//AjxPost.prototype.execute =
		//	function(callback, form, optionalTimeout) {
		
		
		/**
		* Sends this request to the target URL. If there is a callback, the request is
		* performed asynchronously.
		*
		* @param requestStr		[string]		HTTP request string/document
		* @param serverUrl		[string]		request target
		* @param requestHeaders	[Array]*		HTTP request headers
		* @param callback		[AjxCallback]*	callback (for async requests)
		* @param useGet			[boolean]*		if true use GET method, else use POST
			AjxRpcRequest.prototype.invoke =
			function(requestStr, serverUrl, requestHeaders, callback, useGet, timeout) {
		*/
		// Post method (brings up form)
		html.append(
				"function saveTemplateText() { \r\n" +
				"   templateNeedsSave = false;\r\n" + 
				"   var subjectEdit = document.getElementById('subject');\r\n" + 
			    "   var subject = subjectEdit.value;" +
				"   templateTextArea = document.getElementById('templateText');\r\n" + 
			    "   templateText = templateTextArea.value;" +
			    "   log('Template text to save: ' + templateText);\r\n" +
				"   var templateId = getSelectedTemplateId();\r\n" + 
				"   log('saveTemplateText() template id = ' + templateId);\r\n" +
				"   //Set temporary form to current values of selected template id and text\r\n" + 
				"   var textHiddenInput = document.getElementById('temp_form_text_hdn');\r\n" +
				"   textHiddenInput.value = templateText;\r\n" + 
				"   var idHiddenInput = document.getElementById('temp_form_id_hdn');\r\n" +
				"   idHiddenInput.value = templateId;\r\n" + 
				"   var form = document.getElementById('form_temp_text');\r\n" + 
				"   if (form == null) { \r\n" +
				"       alert('Error - could not find form for temp text save');\r\n " +
				"   };\r\n" +
				"   var postString = 'text=' + encodeURI(templateText) + '&subject=' + encodeURI(subject)" +
				"                     + '&templateId=' + templateId;\r\n" +
				"   log('saveTemplateText() - postString' + postString);\r\n" +
				"   post('savetemplatejs.do', postString, handleTemplateSaveResponse, null);\r\n" +
				"   log('saveTemplateText() done executing post of temp form');\r\n" +
				"   var savedDialogDiv = document.getElementById(\"" + this.TEMPLATE_SAVED_POPUP_DIV +  
					    "\");\r\n" + 
				"   savedDialogDiv.style.visibility='visible';\r\n;" +
			    "}\r\n\r\n");

		html.append(
				"function hideTemplateSavedDialog() { \r\n" +
				"   log('hideTemplateSavedDialog() hiding dialog that acknowledges save of template');\r\n" +
				"   var savedDialogDiv = document.getElementById(\"" + this.TEMPLATE_SAVED_POPUP_DIV +  
					    "\");\r\n" + 
				"   savedDialogDiv.style.visibility='hidden';\r\n;" +
			    "}\r\n\r\n");

		html.append(
				"function handleTemplateSaveResponse() { \r\n" +
				"   log('handleTemplateSaveResponse() called'); \r\n" +
			    "}\r\n\r\n");

		html.append(
				"function saveCompleted() { \r\n" +
				"   log('saveCompleted() called'); \r\n" +
				"   alert('saveCompleted() - not implemented'); \r\n" +
			    "}\r\n\r\n");

		
		html.append(
		        "function personSelectedCallback(personId, lastName, firstName, middleName) { \r\n" +
		        "   log('personSelectedCallback() called');" + 
		        " 	var recipient = findRecipient(personId);\r\n" +
				"   if (recipient == null) {\r\n" +
				"      addRecipientData(personId, lastName, firstName + '&nbsp;' + middleName);\r\n" +
				"      refreshRecipientListDisplay();\r\n" +
				"   } else { \r\n" +
		        "       log('personSelectedCallback() - recipient already selected, ignoring new selection.  personId: ' + personId);" + 
				"   } \r\n" +
			    "}\r\n\r\n");

		html.append(
				"function pickRecipientToAdd() { \r\n" +
				"   var newRecipientSearchDiv = new PersonSearchDiv(); \r\n" +
				"   onPersonSelected = personSelectedCallback;\r\n" +
				"   if (onPersonSelected == null) alert('After setting, onPersonSelected is NULL');\r\n" +
				"   newRecipientSearchDiv.showPersonSearchDiv('get.matching.people',50, 100, 'Choose Email Recipient', null) ;\r\n" +
			    "}\r\n\r\n");
		html.append("	</script> \r\n");
	}

	
	public void addTemplateComboArray(StringBuffer html, List<FileEmailTemplateCategory> categories) {
		log.debug("Add an empty entry for selection of 'Select Option:' category option");
		html.append("\r\n\r\n  // Created by " + this.getClass().toString() + ".addTemplateComboArray()");
		html.append("\r\n   categoryOptions = ");
		html.append("'<select name=\"" + TEMPLATE_SELECT_COMBO_NAME
				 + "\"   class=\"formComboClass\"> ' + \r\n");
		html.append("'  </select>   '; \r\n\r\n");
		html.append("  categoryTemplates[0] = categoryOptions;\r\n");
		
		Iterator<FileEmailTemplateCategory> categoryIter = categories.iterator();
		while (categoryIter.hasNext()) {
			FileEmailTemplateCategory category = categoryIter.next();
			Iterator<FileEmailTemplate> templateIter = CoreServiceLocator.getSystemService()
				.findEmailTemplatesForCategory(ThreadProperties.getDomain(), category).iterator();
			String onChange = "getTemplateTextFromWeb(); return false";
			//function findEmailTemplateText(contextRoot, user, domainId, pcode, templateId) {

			html.append("                                                      \r\n");
			html.append("   // ------------------------------------------------ \r\n");
			html.append("   // Templates for Template Category " + category + " \r\n");
			html.append("     categoryOptions =  \r\n");
				
			html.append(" '<select name=\"" + TEMPLATE_SELECT_COMBO_NAME
					 + "\" onChange=\"" + onChange + "\" " +
				 		" class=\"formComboClass\"> ' + \r\n");
			if (templateIter.hasNext()) {
				while (templateIter.hasNext()) {
					FileEmailTemplate template = templateIter.next();
					html.append("       	'<option value=\"" +
							template.getId().toString() +
							"\">" +	template.getName() + "</option>' \r\n");
					if (templateIter.hasNext()) {
						html.append("+ ");
					}
				}
			} 
			html.append("'    </select>   '; \r\n\r\n");
			html.append("  categoryTemplates[" + category.getId().toString() + "] = categoryOptions;\r\n");
		}
	}
	
}
